package com.tanhua.backstage.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.BsMapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.BsUser;
import com.tanhua.common.pojo.User;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserService {
    @Autowired
    private RestTemplate restTemplate;
    //调用单点登录系统的路径头
    @Value("${tanhua.sso.url}")
    private String ssoUrl;
    //盐值
    @Value("${jwt.secret}")
    private String secret;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private BsMapper bsMapper;


    @Autowired
    private UserMapper userMapper;


    /**
     * 提供功能:token校验的服务
     *
     * @param token
     * @return
     */
    public BsUser checkToken(String token) {
        //先从redis中获取token
        String redisToken = redisTemplate.opsForValue().get(token);
        if(StrUtil.isEmpty(redisToken)){
            //redis中token没值，说明已退出，校验token不通过,禁访问其它功能
            return null;
        }

        //解析token
        Map<String, Object> mapBody = Jwts.parser().setSigningKey(secret)
                .parseClaimsJws(token).getBody();
        //2.封装解析的token的用户信息
        BsUser bsUser = new BsUser();
        bsUser.setId(Long.valueOf(mapBody.get("id").toString()));
        bsUser.setUsername(mapBody.get("username").toString());
        QueryWrapper<BsUser> wrapper = new QueryWrapper<>();
        wrapper.eq("id", bsUser.getId());
        BsUser bsUserMapper = bsMapper.selectOne(wrapper);
        bsUser.setAvatar(bsUserMapper.getAvatar());
        //返回用户信息(token)
        return bsUser;
    }

    /**
     * 业务层实现功能:退出登录
     *
     */
    public void logoutBsUser(String token) {
        //将用户的token的缓存数据删除掉,用户就无法通过token校验登录
        redisTemplate.delete(token);
    }

    /**
     * 根据指定时间获取user对象
     * @param startTime
     * @param endTime
     * @return
     */
    public Integer queryUserByTime(Date startTime, Date endTime) {

        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.gt("created", startTime);
        queryWrapper1.lt("created", endTime);
        return this.userMapper.selectCount(queryWrapper1);
    }

    public List<User> queryUserListByTime(Date startTime, Date endTime){

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("created", startTime);
        queryWrapper.lt("created", endTime);

        //新注册的用户
        return this.userMapper.selectList(queryWrapper);
    }
}
